import axios from 'axios'
// import qs from 'qs'
import { DEBUG_MODE } from './../utils/index'
import router from "../router/index"

// import { getAccessToken ,clearAllCookie} from "../js/auth";
// import md5 from '../utils/md5'

// const str = '5c18fb492a746ad1a86f49c4f1e237d3'

var instance = axios.create({
  timeout: 60000 // 1 minute
})

function getQueryStringByName(name) {
  var result = location.search.match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
  if (result == null || result.length < 1) {
    return "";
  }
  return result[1];
}

instance.interceptors.request.use(config => {
  const method = config.method.toUpperCase()
  const data = ['GET', 'DELETE'].includes(method) ? config.params : config.data

  const timestamp = parseInt(Date.now() / 1000)
  // const encryption = md5(str + timestamp)

  // Display request info for debug
  if (DEBUG_MODE) {
    // Filter headers to display
    const headersToDisplay = {}
    for (const k of Object.keys(config.headers)) {
      const value = config.headers[k]
      if (typeof value !== 'object') {
        headersToDisplay[k] = value
      }
    }

    let dataToDisplay = {}
    if (data instanceof FormData) {
      if (data.keys && data.get) {
        const keys = data.keys()
        for (const key of keys) {
          dataToDisplay[key] = data.get(key)
        }
      } else {
        dataToDisplay = data
      }
    } else {
      dataToDisplay = data
    }

    // console.log(`-> Request:  ${method} '${config.url}': `, config, dataToDisplay)
  }

  return config
}, err => Promise.reject(err))
// 响应拦截器
instance.interceptors.response.use(
  response => {
    // 对响应数据进行处理等操作

    // if (response.data.respCode == "00002") {
    //   MessageBox.alert(response.data.respDesc, "登录失效", {
    //     confirmButtonText: "跳转登录页面",
    //     callback: action => {
    //       // 跳转登录页
    //       window.location.href = "/";
    //     }
    //   });
    // } else if (response.data.respCode != "00000") {
    //   if (response.data.respDesc != "") {
    //     ElementUI.Message({
    //       title: "错误",
    //       message: response.data.respDesc,
    //       type: "error"
    //     });
    //   }
    // }
    if (response.data.flag == 401) {
      const code = getQueryStringByName("invitationCode");
      const type = getQueryStringByName("type");
      window.location.href = "/login?invitationCode=" + code + "&type=" + type;
    };
    return response;

  },
  error => {
    if (window.location.pathname == '/h5/vip') {
      return Promise.reject(error);
    }
    if (error.response.data && (error.response.status === 460 || error.response.status === 401 || error.response.status === 550)) {
      // 如果响应状态为401，说明用户未登录或登录已过期，需要重新登录
      localStorage.clear();
      const code = getQueryStringByName("invitationCode");
      const type = getQueryStringByName("type");
      router.push({ path: "/login", query: { invitationCode: code, type: type } })
    } else {
      // 其他错误状态码处理
      // ...
    }
    return Promise.reject(error)
  }
)

class Requester {
  static get(url = '', data = {}, opts = {}) {
    const config = {
      headers: {
        'Content-Type': 'application/json',
        'platform': 'PC',
        'client': '0',
        'Authorization': "Bearer " + localStorage.getItem('access_token')
      },
      params: data,
    }
    return instance.get(url, config).then(res => res.data)
  }

  static post(url = '', data = {}, opts = {}) {
    let token = null
    if (url != "/doctor-cheese/auth/v1/login/pn" && url != "/doctor-cheese/auth/v1/login/pp") {
      token = "Bearer " + localStorage.getItem('access_token')
    }
    const config = {
      headers: {
        'Content-Type': 'application/json',
        'platform': 'PC',
        'client': '0',
        'Authorization': token
      },
      // transformRequest: [
      //   data => qs.stringify(data)
      // ]
    }
    return instance.post(url, data, config).then(res => res.data)
  }

  static put(url = '', data = {}, opts = {}) {
    const config = {
      headers: {
        'Content-Type': 'application/json',
        'platform': 'PC',
        'client': '0',
        'Authorization': "Bearer " + localStorage.getItem('access_token')
      },
      // transformRequest: [
      //   data => qs.stringify(data)
      // ]
    }
    return instance.put(url, data, config).then(res => res.data)
  }

  static delete(url = '', data = {}, opts = {}) {
    const config = {
      headers: {
        'Content-Type': 'application/json',
        'platform': 'PC',
        'client': '0',
        'Authorization': "Bearer " + localStorage.getItem('access_token')
      },
      params: data,
    }
    return instance.delete(url, config).then(res => res.data)
  }

  // data can be either FormData or plain object
  static async formdata(url = '', data = {}, opts = {}) {
    const config = {
      headers: { 'Content-Type': 'multipart/form-data' }
    }

    let preparedData = null
    if (data instanceof window.FormData) {
      preparedData = data
    } else {
      preparedData = new window.FormData()
      Object.keys(data).forEach(key => {
        preparedData.append(key, data[key])
      })
    }

    const res = await instance.post(url, preparedData, config);
    return res.data;
  }

  static upload(url = '', data = {}, opts = {}) {
    const config = {
      headers: {
        'Content-Type': "multipart/form-data",
        'platform': 'PC',
        'client': '0',
        'Authorization': "Bearer " + localStorage.getItem('access_token')
      },
      // transformRequest: [
      //   data => qs.stringify(data)
      // ]
    }
    return instance.post(url, data, config).then(res => res.data)
  }
}

export default Requester
